<script setup lang="ts">
import { computed, reactive, watch } from 'vue';
import { useBoolean } from '@sa/hooks';
import { fetchAddCodegenerator, fetchUpdateCodegenerator } from '@/service/api';
import { useFormRules, useNaiveForm } from '@/hooks/common/form';
import { $t } from '@/locales';
import { enableStatusOptions } from '@/constants/business';

defineOptions({
  name: 'CodegeneratorOperateDrawer'
});

interface Props {
  /** the type of operation */
  operateType: NaiveUI.TableOperateType;
  /** the edit row data */
  rowData?: Api.SystemManage.Codegenerator | null;
}

const props = defineProps<Props>();

interface Emits {
  (e: 'submitted'): void;
}

const emit = defineEmits<Emits>();

const visible = defineModel<boolean>('visible', {
  default: false
});

const { formRef, validate, restoreValidation } = useNaiveForm();
const { defaultRequiredRule } = useFormRules();

const title = computed(() => {
  const titles: Record<NaiveUI.TableOperateType, string> = {
    add: '新增代码生成管理',
    edit: '编辑代码生成管理'
  };
  return titles[props.operateType];
});

// 动态生成 Model 类型
type Model = {
  fieldName: string | null;
  fieldType: string | null;
  fieldDescription: string | null;
  fieldDefaultValue: string | null;
  fieldIsKey: boolean | null;
  fieldIsNullable: boolean | null;
  fieldIsUnique: boolean | null;
  fieldIsAutoIncrement: boolean | null;
};

const model: Model = reactive(createDefaultModel());

function createDefaultModel(): Model {
  return {
    fieldName: null,
    fieldType: null,
    fieldDescription: null,
    fieldDefaultValue: null,
    fieldIsKey: null,
    fieldIsNullable: null,
    fieldIsUnique: null,
    fieldIsAutoIncrement: null,
  };
}

type RuleKey = Extract<keyof Model, 'fieldName' | 'fieldType' | 'fieldDescription' | 'fieldDefaultValue' | 'fieldIsKey' | 'fieldIsNullable' | 'fieldIsUnique' | 'fieldIsAutoIncrement'>;

const rules: Record<RuleKey, App.Global.FormRule> = {
  fieldName: defaultRequiredRule,
};

const roleId = computed(() => props.rowData?.id || -1);

const isEdit = computed(() => props.operateType === 'edit');

function handleInitModel() {
  Object.assign(model, createDefaultModel());

  if (props.operateType === 'edit' && props.rowData) {
    Object.assign(model, props.rowData);
  }
}

function closeDrawer() {
  visible.value = false;
}

async function handleSubmit() {
  await validate();
  let res = null;
  // request
  if (props.operateType === 'edit') {
    res = await fetchUpdateCodegenerator(model);
  } else {
    res = await fetchAddCodegenerator(model);
  }
  const { error, data } = res;
  if (error) {
    return;
  }
  window.$message?.success($t('common.updateSuccess'));
  closeDrawer();
  emit('submitted');
}

watch(visible, () => {
  if (visible.value) {
    handleInitModel();
    restoreValidation();
  }
});
</script>

<template>
  <NDrawer v-model:show="visible" display-directive="show" :width="360">
    <NDrawerContent :title="title" :native-scrollbar="false" closable>
      <NForm ref="formRef" :model="model" :rules="rules">
        <NFormItem v-if="!column.is_key" :label="column.description" :path="column.name">
          <NInput v-model:value="model[column.name]" :placeholder="column.description" />
        </NFormItem>
        <NFormItem v-if="!column.is_key" :label="column.description" :path="column.name">
          <NInput v-model:value="model[column.name]" :placeholder="column.description" />
        </NFormItem>
        <NFormItem v-if="!column.is_key" :label="column.description" :path="column.name">
          <NInput v-model:value="model[column.name]" :placeholder="column.description" />
        </NFormItem>
        <NFormItem v-if="!column.is_key" :label="column.description" :path="column.name">
          <NInput v-model:value="model[column.name]" :placeholder="column.description" />
        </NFormItem>
        <NFormItem v-if="!column.is_key" :label="column.description" :path="column.name">
          <NInput v-model:value="model[column.name]" :placeholder="column.description" />
        </NFormItem>
        <NFormItem v-if="!column.is_key" :label="column.description" :path="column.name">
          <NInput v-model:value="model[column.name]" :placeholder="column.description" />
        </NFormItem>
        <NFormItem v-if="!column.is_key" :label="column.description" :path="column.name">
          <NInput v-model:value="model[column.name]" :placeholder="column.description" />
        </NFormItem>
        <NFormItem v-if="!column.is_key" :label="column.description" :path="column.name">
          <NInput v-model:value="model[column.name]" :placeholder="column.description" />
        </NFormItem>
      </NForm>
      <template #footer>
        <NSpace :size="16">
          <NButton @click="closeDrawer">{{ $t('common.cancel') }}</NButton>
          <NButton type="primary" @click="handleSubmit">{{ $t('common.confirm') }}</NButton>
        </NSpace>
      </template>
    </NDrawerContent>
  </NDrawer>
</template>

<style scoped></style>